#!/usr/bin/env python3
"""
MCP 演示一键启动脚本
自动安装依赖、启动服务器、打开浏览器演示
"""
import os
import sys
import time
import webbrowser
import subprocess
import signal
from pathlib import Path


def check_dependencies():
    """检查并安装依赖"""
    print("📦 检查项目依赖...")
    
    try:
        import fastapi, uvicorn, httpx, websockets, aiofiles
        print("✅ 所有依赖已安装")
        return True
    except ImportError as e:
        print(f"❌ 缺少依赖: {e}")
        print("🔄 正在安装依赖...")
        
        try:
            subprocess.check_call([sys.executable, "-m", "pip", "install", "-r", "requirements.txt"])
            print("✅ 依赖安装完成")
            return True
        except subprocess.CalledProcessError:
            print("❌ 依赖安装失败，请手动运行: pip install -r requirements.txt")
            return False


def start_server():
    """启动MCP服务器"""
    print("🚀 启动 MCP Server...")
    
    # 检查端口是否被占用
    import socket
    sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    result = sock.connect_ex(('localhost', 8000))
    sock.close()
    
    if result == 0:
        print("⚠️  端口8000已被占用，尝试终止现有进程...")
        try:
            # Windows
            os.system("netstat -ano | findstr :8000")
            os.system("taskkill /f /im python.exe 2>nul")
        except:
            try:
                # Unix/Linux
                os.system("lsof -ti:8000 | xargs kill -9 2>/dev/null")
            except:
                pass
        time.sleep(2)
    
    # 启动服务器
    try:
        server_process = subprocess.Popen([
            sys.executable, "-m", "uvicorn", 
            "mcp_server:app", 
            "--host", "0.0.0.0", 
            "--port", "8000",
            "--log-level", "info"
        ], stdout=subprocess.PIPE, stderr=subprocess.PIPE)
        
        print("⏳ 等待服务器启动...")
        time.sleep(3)
        
        # 检查服务器是否启动成功
        import urllib.request
        try:
            urllib.request.urlopen("http://localhost:8000/api/status", timeout=5)
            print("✅ MCP Server 启动成功!")
            return server_process
        except:
            print("❌ 服务器启动失败")
            server_process.terminate()
            return None
            
    except Exception as e:
        print(f"❌ 启动服务器时出错: {e}")
        return None


def open_browser():
    """打开浏览器展示Web界面"""
    print("🌐 打开浏览器...")
    
    urls = [
        "http://localhost:8000",
        "http://localhost:8000/docs"
    ]
    
    for url in urls:
        try:
            webbrowser.open(url)
            time.sleep(1)
        except:
            print(f"⚠️  无法自动打开浏览器，请手动访问: {url}")


def run_client_demo():
    """运行客户端演示"""
    print("\n" + "="*60)
    print("🎬 MCP 客户端演示")
    print("="*60)
    
    choice = input("是否运行客户端演示？(y/n): ").lower().strip()
    
    if choice in ['y', 'yes', '是', '']:
        try:
            subprocess.run([sys.executable, "mcp_client.py"], check=True)
        except subprocess.CalledProcessError:
            print("❌ 客户端演示运行失败")
        except KeyboardInterrupt:
            print("\n⏹️  客户端演示被用户中断")


def show_usage_info():
    """显示使用说明"""
    print("\n" + "="*60)
    print("📋 MCP 演示使用说明")
    print("="*60)
    print("1. 🌐 Web界面: http://localhost:8000")
    print("   - 查看服务器能力")
    print("   - 交互式调用工具、获取资源、渲染提示")
    print("   - 实时WebSocket通知")
    print()
    print("2. 📚 API文档: http://localhost:8000/docs")
    print("   - FastAPI自动生成的交互式文档")
    print("   - 可直接测试所有API端点")
    print()
    print("3. 🔧 命令行工具:")
    print("   - python mcp_client.py  # 运行完整客户端演示")
    print("   - curl http://localhost:8000/capabilities  # 获取服务器能力")
    print()
    print("4. 📁 生成的文件:")
    print("   - temp_files/  # 演示过程中创建的文件")
    print("   - 包括代码审查报告、系统日志等")
    print()
    print("5. ⏹️  停止服务器: Ctrl+C")


def cleanup(server_process):
    """清理资源"""
    print("\n🧹 清理资源...")
    
    if server_process and server_process.poll() is None:
        print("⏹️  正在关闭服务器...")
        server_process.terminate()
        time.sleep(2)
        
        if server_process.poll() is None:
            server_process.kill()
        
        print("✅ 服务器已关闭")


def main():
    """主函数"""
    print("🎉 MCP (Model Context Protocol) 演示启动器")
    print("="*60)
    print("本脚本将:")
    print("1. 检查并安装项目依赖")
    print("2. 启动MCP服务器")
    print("3. 打开浏览器Web界面")
    print("4. 可选运行客户端演示")
    print("="*60)
    
    # 检查当前目录
    if not Path("mcp_server.py").exists():
        print("❌ 请在项目根目录运行此脚本")
        sys.exit(1)
    
    # 检查依赖
    if not check_dependencies():
        sys.exit(1)
    
    # 启动服务器
    server_process = start_server()
    if not server_process:
        sys.exit(1)
    
    try:
        # 打开浏览器
        open_browser()
        
        # 显示使用说明
        show_usage_info()
        
        # 运行客户端演示
        run_client_demo()
        
        # 等待用户操作
        print("\n" + "="*60)
        print("🎯 MCP Server 正在运行...")
        print("按 Ctrl+C 停止服务器")
        print("="*60)
        
        # 保持服务器运行
        try:
            while True:
                time.sleep(1)
        except KeyboardInterrupt:
            print("\n⏹️  收到停止信号...")
    
    finally:
        cleanup(server_process)
    
    print("\n🎊 MCP 演示结束，感谢使用!")


if __name__ == "__main__":
    main() 